package com.culture.bootdemo.utils;

import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @Author: wen
 * @DateTime: 2024/2/18 17:15
 * @Description: Okhttp
 **/
public class HttpClientOkUtil {

    public static String okHttpGetMethod(String url) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url).build();
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
        assert response != null;
        if (response.isSuccessful()) {
            return response.body() == null ? "" : response.body().string();
        }
        return null;
    }


    public static String okHttpPostMethod(String url, String body) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setConnectTimeout(3000, TimeUnit.MILLISECONDS);
        MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");
        Request request = new Request.Builder()
                .url(url).post(RequestBody.create(JSON_TYPE, body)).addHeader("Content-Type", "application/json")
                .build();
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
        assert response != null;
        if (response.isSuccessful()) {
            return response.body() == null ? "" : response.body().string();
        }
        return null;
    }


}
